import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/live/live_gift_logic.dart';
import 'package:sports_new/entity/live/live_board_entity.dart';
import 'package:sports_new/entity/live/live_gift_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/user.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/view/my/my_recharge_page.dart';
import 'package:sports_new/widgets/max_bottom_sheet.dart';
import 'package:sports_new/widgets/base/qkd_image.dart';
import 'package:sports_new/widgets/base/qkd_indicator.dart';
import 'package:sports_new/widgets/base/qkd_text.dart';
import 'package:visibility_detector/visibility_detector.dart';
import '../../../widgets/circular.dart';
import '../../../widgets/slide_transition_x.dart';

class GiftBottomSheet extends StatefulWidget {
  const GiftBottomSheet({super.key, required this.liveId});

  final int? liveId;

  @override
  State<GiftBottomSheet> createState() => _GiftBottomSheetState();
}

class _GiftBottomSheetState extends State<GiftBottomSheet> {
  late final LiveGiftLogic logic;

  @override
  void initState() {
    logic = Get.put(LiveGiftLogic(),tag: "${widget.liveId}");
    logic.liveId = widget.liveId;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<LiveGiftLogic>(
      tag: "${widget.liveId}",
      builder: (logic) {
        return MaxBottomSheet(
          onClosing: (){},
          clipBehavior: Clip.antiAlias,
          elevation: 20,
          constraints: BoxConstraints(maxHeight: Get.height*348/812),
          shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(12))
          ),
          builder: (context) => VisibilityDetector(
            onVisibilityChanged: (info) async{
              if(!info.visibleBounds.isEmpty){
                await User.fetchUserInfo(fetchFocus: false);
                setState(() {});
              }
            },
            key: const Key("giftSheet"),
            child: AnimatedContainer(
              color: logic.tabController.index == 0?Colours.black161922:Colours.white,
              duration: const Duration(milliseconds: 300),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(height: 16),
                  AnimatedCrossFade(
                    alignment: Alignment.centerLeft,
                    firstCurve: Curves.easeIn,
                    secondCurve: Curves.easeOut,
                    layoutBuilder: (topChild, topChildKey,
                        bottomChild, bottomChildKey){
                      return Stack(
                        alignment: AlignmentDirectional.topStart,
                        children: [
                          Positioned(
                            key: bottomChildKey,
                            top: 0,
                            child: bottomChild,
                          ),
                          Positioned(
                            key: topChildKey,
                            child: topChild,
                          ),
                        ],
                      );
                    },
                    firstChild: AnimatedCrossFade(
                      firstCurve: Curves.easeInSine,
                      secondCurve: Curves.easeOutSine,
                      firstChild: QkdText(
                        "赠送主播一个小礼物吧～",
                        fontSize: 12,color: Colours.white.withOpacity(0.5)
                      ).paddingOnly(left: 12,bottom: 24,top: 8),
                      secondChild: numList().paddingOnly(bottom: 16),
                      crossFadeState: logic.showNumList?CrossFadeState.showSecond:CrossFadeState.showFirst,
                      duration: const Duration(milliseconds: 150)
                    ),
                    secondChild: Container(),
                    crossFadeState: logic.tabController.index == 0?CrossFadeState.showFirst:CrossFadeState.showSecond,
                    duration: const Duration(milliseconds: 300),
                  ),
                  choiceBar(),
                  Container(height: 16),
                  Expanded(
                    child: AnimatedSwitcher(
                      duration: const Duration(milliseconds: 300),
                      transitionBuilder: (child, animation) =>
                        SlideTransitionX(position: animation, child: child),
                      child: logic.tabController.index == 0?giftList():rankList(),
                    )
                  )
                ],
              ),
            ),
          )
        );
      }
    );
  }
  
  Widget choiceBar(){
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 12),
      child: Row(
        children: [
          Expanded(
            child: Styles.tabbar(
              controller: logic.tabController,
              tabs: const [Text("礼物"),Text("榜单")],
              labelColor: Colours.redF56060,
              unselectedLabelColor: Colours.grey66,
              fontWeight: FontWeight.w500,
              scrollable: true,
              labelPadding: const EdgeInsets.only(right: 16),
              indicator: const QkdIndicator.none(),
              onTap: (index) => setState(() {})
            ),
          ),
          AnimatedCrossFade(
            alignment: Alignment.center,
            firstChild: GestureDetector(
              onTap: () {
                Utils.onEvent('zbjcz',params: {'zbjsp':'qb_button'});
                Get.bottomSheet(
                  const RechargePage.sheet(),
                  barrierColor: Colours.transparent
                );
              },
              child: Circular(
                radius: 4,
                color: Colours.white.withOpacity(0.1),
                padding: const EdgeInsets.symmetric(vertical: 2),
                child: Row(
                  children: [
                    Container(width: 4),
                    Image.asset(Utils.getImgPath("plan_coin.png"),width: 14),
                    Container(width: 4),
                    QkdText("${User.info?.qiuGold??0}",
                      fontSize: 12,color: Colours.white
                    ),
                    Image.asset(
                        Utils.getImgPath('arrow_right_36.png'),
                        width: 12
                    ),
                    Container(width: 2)
                  ],
                )
              ),
            ),
            secondChild: const QkdText(
              "球币",
              fontSize: 12,color: Colours.grey99
            ),
            crossFadeState: logic.tabController.index == 0?CrossFadeState.showFirst:CrossFadeState.showSecond,
            duration: const Duration(milliseconds: 300),
          )
        ],
      ),
    );
  }
  
  Widget giftList(){
    return Stack(
      children: [
        ScrollConfiguration(
          behavior: const ScrollBehavior().copyWith(overscroll: false),
          child: GridView.builder(
              controller: logic.scrollController,
              padding: const EdgeInsets.fromLTRB(8,0,8,2),
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 4,
                  childAspectRatio: 84/100,
                  crossAxisSpacing: 8,
                  mainAxisSpacing: 8,
                  mainAxisExtent: 100
              ),
              itemCount: logic.gifts?.length??0,
              itemBuilder: (context,index)=> giftItem(index)
          ),
        ),
        if(logic.showTopShader)
        Positioned(
          top: 0, left: 0,right: 0,
          child: shader(Alignment.topCenter)
        ),
        if(logic.showBottomShader)
        Positioned(
          bottom: 0, left: 0,right: 0,
          child: shader(Alignment.bottomCenter)
        )
      ],
    );
  }

  Widget rankList(){
    return Stack(
      alignment: Alignment.bottomCenter,
      children: [
        ScrollConfiguration(
          behavior: const ScrollBehavior().copyWith(overscroll: false),
          child: MediaQuery.removePadding(
            context: context,
            removeTop: true,
            child: ListView.builder(
              itemCount: logic.tops?.length??0,
              itemBuilder: (context, index) => rankItem(index)
            ),
          ),
        ),
        const Divider(height: 0.5,color: Colours.greyEE),
        SafeArea(child: rankItem(logic.userRank??99,isSelf: true))
      ],
    );
  }
  
  Widget giftItem(int index){
    GiftEntity entity = logic.gifts![index];
    return GestureDetector(
      onTap: () => logic.selectGift(index),
      onLongPress: () => logic.showGiftNumList(index),
      child: Stack(
        children: [
          Column(
            children: [
              Container(height: logic.giftIndex == index?3:6),
              QkdImage(
                imageUrl: entity.logo,
                width: 60,
                height: 60,
                fit: BoxFit.cover,
              ),
              if(logic.giftIndex != index)
              QkdText(entity.name,fontSize: 12,color: Colours.white).paddingOnly(top: 2),
              QkdText(
                "${entity.priceStr}球币",
                fontSize: logic.giftIndex == index?9:10,
                color: Colours.white.withOpacity(0.5)
              )
            ],
          ),
          if(logic.giftIndex == index)
          Circular(
            color: Colours.blueD3E4FF.withOpacity(0.15),
            radius: 8,
            clipBehavior: Clip.antiAlias,
            child: Column(
              children: [
                Container(height: 75),
                GestureDetector(
                  onTap: () => logic.payGift(index),
                  child: Container(
                    width: Get.width,height: 25,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: logic.showNumList?Colours.grey5C5E64:null,
                      gradient: logic.showNumList?null:const LinearGradient(
                        colors: [Color(0xFFF54D4F),Color(0xFFF53C6A)],
                      )
                    ),
                    child: const QkdText(
                      "赠送",
                      fontSize: 12,
                      color: Colours.white,
                    ),
                  ),
                )
              ],
            )
          )
        ],
      ),
    );
  }

  Widget rankItem(int index,{bool isSelf = false}){
    BoardEntity entity = isSelf?logic.userBoard:logic.tops![index];
    String rank = isSelf?(logic.userRank!=null?"${logic.userRank!+1}":"-"):"${index+1}";
    List<Color> bgColor = [Colours.white,Colours.white];
    Color textColor = Colours.grey99;
    if(index == 0){
      bgColor = [Colours.yellowFFE265.withOpacity(0.2),Colours.yellowFFE265.withOpacity(0)];
      textColor = Colours.orangeE4800A;
    }else if(index == 1){
      bgColor = [Colours.blueB7CCDC.withOpacity(0.2),Colours.blueB7CCDC.withOpacity(0)];
      textColor = Colours.blue859EB2;
    }else if(index == 2){
      bgColor = [Colours.goldDEB574.withOpacity(0.2),Colours.goldDEB574.withOpacity(0)];
      textColor = Colours.goldBC773D;
    }
    return Circular(
      height: 52,
      gradient: LinearGradient(colors: bgColor,stops: const [0.1,0.9]),
      child: Row(
        children: [
          Container(
            width: 52,
            alignment: Alignment.center,
            child: QkdText(
              rank,
              fontSize: 18,
              color: textColor,
              fontFamily: "Din",
              fontWeight: FontWeight.w600
            ),
          ),
          Stack(
            clipBehavior: Clip.none,
            children: [
              QkdImage(
                imageUrl: entity.userAvatar??"",
                shape: BoxShape.circle,
                width: 40,height: 40
              ),
              if(index == 0)
              Positioned(
                top: -6,left: -6,
                child: Image.asset(
                  Utils.getImgPath('live_tops_icon.png'),
                  width: 20,height: 20
                ),
              )
            ],
          ),
          Container(width: 8),
          QkdText(entity.userName??""),
          const Spacer(),
          QkdText("${entity.totalGold??"-"}",
            fontSize: 12,
            fontWeight: FontWeight.w500,
            color: textColor
          ),
          Container(width: 12)
        ],
      ),
    );
  }

  Widget numList(){
    GiftEntity? entity = logic.giftIndex!= null?(logic.gifts?[logic.giftIndex??0]):null;
    return SizedBox(
      height: 32,
      child: ScrollConfiguration(
        behavior: const ScrollBehavior().copyWith(overscroll: false),
        child: MediaQuery.removePadding(
          context: context,
          removeLeft: true,
          child: ListView(
            scrollDirection: Axis.horizontal,
            padding: const EdgeInsets.symmetric(horizontal: 11),
            children: List<Widget>.generate(
              entity?.giftUnit?.length??0,
              (index) => GestureDetector(
                onTap: () => logic.payGiftNum(entity,index),
                child: Circular(
                  width: 77,height: 32,
                  radius: 4,
                  alignment: Alignment.center,
                  gradient: const LinearGradient(
                    colors: [Color(0xFFF54D4F),Color(0xFFF53C6A)],
                  ),
                  child: QkdText(
                    "${entity!.giftUnit![index]}个",
                    fontSize: 12,
                    color: Colours.white,
                  ),
                ),
              )
            ).insertEvery(Container(width: 8))
          ),
        ),
      ),
    );
  }

  Widget shader(Alignment align){
    List<Color> colors = [Colours.black161922,Colours.black161922.withOpacity(0)];
    return Container(
      height: 34,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: align == Alignment.topCenter?colors:colors.reversed.toList(),
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter
        )
      ),
    );
  }
}
